package com.shuquanlian.os;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.webkit.WebResourceError;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.Manifest;
import androidx.core.content.ContextCompat;
import android.content.pm.PackageManager;
import androidx.core.app.ActivityCompat;
import androidx.annotation.NonNull;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private WebView webView;
    private ProgressBar progressBar;
    private static final int PERMISSION_REQUEST_CODE = 100;
    private static final String TARGET_URL = "https://shuquanlian.xhpmm.com";
//    private static final String TARGET_URL = "https://paas.huifu.com/checkout/demo/h5/cashier.html?price=0.02&pageShowType=fullScreen";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(Color.WHITE);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(
                            View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        // 初始化视图
        webView = (WebView) findViewById(R.id.webView);
        progressBar = findViewById(R.id.progressBar);

        // 请求权限
        requestPermissions();

        // 配置WebView
        setupWebView();

    }
    private void requestPermissions() {
        String[] permissions = {
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_NETWORK_STATE
        };

        boolean allPermissionsGranted = true;
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                allPermissionsGranted = false;
                break;
            }
        }

        if (!allPermissionsGranted) {
            ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
        } else {
            // 权限已授予，加载网页
            webView.loadUrl(TARGET_URL);
        }
    }

    private void setupWebView() {
        WebSettings webSettings = webView.getSettings();

        // 启用JavaScript
        webSettings.setJavaScriptEnabled(true);

        // 启用DOM存储
        webSettings.setDomStorageEnabled(true);

        // 启用数据库
        webSettings.setDatabaseEnabled(true);
        String databasePath = this.getApplicationContext().getDir("database", MODE_PRIVATE).getPath();
        webSettings.setDatabasePath(databasePath);

        // 启用缓存
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { // Android 13 (API 33) 及以上废弃
//            webSettings.setAppCacheEnabled(true);
//            webSettings.setAppCachePath(getCacheDir().getAbsolutePath());
        }
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);

        // 其他设置
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setDisplayZoomControls(false);
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowContentAccess(true);
        // user-agent设置
//        String userAgent = webSettings.getUserAgentString();
//        if (!userAgent.contains("shuquanlianBot")) {
//            webSettings.setUserAgentString(userAgent + " shuquanlianBot/1.0");
//        }


        // 设置WebViewClient
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                // 在WebView内部加载链接，而不是使用外部浏览器
//                view.loadUrl(request.getUrl().toString());

                String url = request.getUrl().toString();
                // 定义微信和支付宝协议和中文名称数组，二维数组
                String[][] paymentMethods = {
                        {"weixin://", "微信"},
                        {"alipays://", "支付宝"}
                };

                // 检测是否是微信或支付宝链接
                for (String[] method : paymentMethods) {
                    if (url.startsWith(method[0])) {
                        try {
                            // 创建Intent启动对应应用
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                            startActivity(intent);
                            return true; // 已处理该链接
                        } catch (ActivityNotFoundException e) {
                            // 未安装对应应用的情况
                            Toast.makeText(MainActivity.this, "请先安装" + method[1] + "应用", Toast.LENGTH_SHORT).show();
                            return true;
                        }
                    }
                }
                return false;
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                // 页面加载完成时可以执行的操作
//                Toast.makeText(MainActivity.this, "加载完成", Toast.LENGTH_SHORT).show();
            }
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                // 处理错误，如加载自定义的错误页面等
                // 打印日志
                System.out.println("Error loading URL: " + error.getDescription());
            }
        });

        // 设置WebChromeClient
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // 更新进度条
                if (newProgress < 100) {
                    progressBar.setVisibility(View.VISIBLE);
                    progressBar.setProgress(newProgress);
                } else {
                    progressBar.setVisibility(View.GONE);
                }
            }
        });
    }

    // 处理返回键事件
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    // 处理权限请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean allGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                    break;
                }
            }

            if (allGranted) {
                webView.loadUrl(TARGET_URL);
            } else {
                Toast.makeText(this, "需要权限才能正常运行应用", Toast.LENGTH_LONG).show();
            }
        }
    }

    // 防止WebView内存泄漏
    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.destroy();
        }
        super.onDestroy();
    }


}